package com.LachesismStorm.lachesism.core.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;

public class QRCodeGenerator {

    private static final int QR_CODE_SIZE = 300; // 二维码大小

    public static BufferedImage generateQRCode(String content) {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        try {
            BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, QR_CODE_SIZE, QR_CODE_SIZE);
            BufferedImage image = new BufferedImage(QR_CODE_SIZE, QR_CODE_SIZE, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = image.createGraphics();

            // 设定背景颜色为白色
            graphics.setColor(Color.WHITE);
            graphics.fillRect(0, 0, QR_CODE_SIZE, QR_CODE_SIZE);

            // 设定二维码颜色为黑色
            graphics.setColor(Color.BLACK);
            for (int x = 0; x < QR_CODE_SIZE; x++) {
                for (int y = 0; y < QR_CODE_SIZE; y++) {
                    if (bitMatrix.get(x, y)) {
                        graphics.fillRect(x, y, 1, 1);
                    }
                }
            }
            graphics.dispose();
            return image;
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String generateQRCodeBase64(String content) {
        BufferedImage image = generateQRCode(content);
        if (image != null) {
            try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
                ImageIO.write(image, "png", outputStream);
                byte[] imageBytes = outputStream.toByteArray();
                return Base64.getEncoder().encodeToString(imageBytes);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static void main(String[] args) {
        String qrContent = "https://www.yunox.cn"; // 需要生成二维码的内容
        String base64QRCode = generateQRCodeBase64(qrContent);
        if (base64QRCode != null) {
            System.out.println("Base64 二维码数据:");
            System.out.println("data:image/png;base64," + base64QRCode);
        } else {
            System.out.println("二维码生成失败");
        }
    }
}